require 'json'

#
# This is the main t.rb module
#
module TRB
  DEFAULT_CONFIG = {
    task_list: '.tasks.json'
  }

  # The primary class that manages getting, saving and printing tasks
  class TaskManager
    def initialize(config)
      @config = config
      @tasks = []

      load_from_file if File.exist?(@config[:task_list])
    end

    def insert(task)
      @tasks << { task: task, id: generate_id }
    end

    def save
      File.open(@config[:task_list], 'w') do |f|
        data = { tasks: @tasks }

        json = JSON.pretty_generate(data)

        f.write(json)
      end
    end

    def display
      @tasks.each do |task|
        puts "#{task['id']} - #{task['task']}"
      end
    end

    def edit(id, updated)
      @tasks.each do |task|
        task[:task] = updated if task['id'] == id.to_i || task[:id] == id.to_i
      end
    end

    def finish(id)
      @tasks.delete_if { |t| t['id'] == id.to_i || t[:id] == id.to_i }
    end

    private

    def load_from_file
      File.open(@config[:task_list]) do |file|
        @tasks = JSON.parse(file.read)['tasks']
      end
    end

    def generate_id
      latest_task = @tasks.last

      if latest_task.nil?
        1
      else
        (latest_task[:id] || latest_task['id']) + 1
      end
    end
  end
end
